package com.dotstone.chipism.activity;

import java.util.HashMap;
import java.util.List;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.listener.CallbackOnInfraredSended;
import com.dotstone.chipism.listener.IInfraredDevice;
import com.dotstone.chipism.listener.IInfraredSeneder;
import com.dotstone.chipism.listener.InfraredDevice;
import com.dotstone.chipism.listener.InfraredSeneder;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.Util;
import com.tiqiaa.client.IRemoteClient;
import com.tiqiaa.client.IRemoteClient.CallBackOnRemoteUploaded;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.constant.ApplianceType;
import com.tiqiaa.icontrol.util.RemoteUtils;
import com.tiqiaa.ircode.IInfraredFetcher;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.IRemoteManager;
import com.tiqiaa.remote.entity.AirRemoteState;
import com.tiqiaa.remote.entity.AirTemp;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.Remote;
import com.tiqiaa.remote.impl.RemoteManager;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class RemoteActivity extends Activity implements
		CallbackOnInfraredSended {
	private final static String TAG = "RemoteActivity";

	public final static String INTENT_PARAMS_REMOTE_JSON = "intent_params_remote_json";

	TextView txt_remote_name;// 遥控器名字
	TextView txtview_mode;// 模式
	TextView txtview_temp;// 温度
	TextView txtview_temp_symbol;

	TextView txtview_wind_amout;// 风量

	View rlayout_air_screen;// 空调状态展示屏

	ListView listview_remote_key;// 按键展示

	Remote mRemote;
	Handler mHandler = new Handler(Looper.getMainLooper());
	private static int initTemp;
	IInfraredDevice mDevice;
	private static HashMap<Integer, String> cmdMap = new HashMap<Integer, String>();
	private EditText mTempEd;
	private Button mSendBtn;
	private MySocket socket;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_remote);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		mDevice = new InfraredDevice();
		// 初始化控件
		rlayout_air_screen = this.findViewById(R.id.rlayout_air_screen);
		txt_remote_name = (TextView) this.findViewById(R.id.txt_remote_name);
		txtview_mode = (TextView) this.findViewById(R.id.txtview_mode);
		txtview_temp = (TextView) this.findViewById(R.id.txtview_temp);
		mTempEd = (EditText)this.findViewById(R.id.temp_input);
		mSendBtn = (Button)this.findViewById(R.id.send_btn);
		txtview_temp_symbol = (TextView) this
				.findViewById(R.id.txtview_temp_symbol);
		txtview_wind_amout = (TextView) this
				.findViewById(R.id.txtview_wind_amout);
		listview_remote_key = (ListView) this
				.findViewById(R.id.listview_remote_key);
		// 获取遥控器ID
		String remoteId = this.getIntent().getStringExtra(
				INTENT_PARAMS_REMOTE_JSON);
		Log.e("wmy", "获取遥控器ID = " + remoteId);
		// 如果遥控器ID非空
		if (remoteId != null && remoteId.equals("") == false) {
			// 遥控器管理类
			RemoteManager manager = new RemoteManager();
			// 通过ID获取遥控器
			mRemote = manager.getRemoteByID(remoteId);
		}

		if (mRemote == null) {
			txt_remote_name.setText("未接收到遥控器参数");
			txt_remote_name.setTextColor(Color.RED);
		} else {
			// 获取遥控器名字
			txt_remote_name.setText(RemoteUtils.getRemoteName(mRemote));

			// 如果是空调，则显示状态屏
			if (mRemote.getType() == ApplianceType.AIR_CONDITIONER) {
				rlayout_air_screen.setVisibility(View.VISIBLE);
				showAirState();
//				initKeys();
			} else {
				// 不是空调 不显示状态屏
				rlayout_air_screen.setVisibility(View.GONE);
			}
			// 初始化按键展示
			KeyAdapter mKeyAdapter = new KeyAdapter(getApplicationContext(),
					mRemote, this);
			listview_remote_key.setAdapter(mKeyAdapter);
		}
		mSendBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String temp = mTempEd.getText().toString();
				int value = Integer.parseInt(temp);
//				String cmd = cmdMap.get(value);
//				SocketManager.getInstance().getSocket().sendMqttData(cmd);
//				AirRemoteState mState = new AirRemoteState(mRemote.getId());
				InfraredFetcher  mFetcher = new InfraredFetcher(getApplicationContext());
				AirRemoteState mState = mFetcher.getAirRemoteStatus(mRemote);
				List<Infrared> irList = mFetcher.fetchAirInfrareds(mRemote, mState, mState.getPower(), mState.getMode(),
						mState.getWind_amount(), AirTemp.getAirTemp(value));
				Log.i("wmy", "根据度数 "+value+" 获取指令 = "+irList.size());
				for (int i = 0; i < irList.size(); i++) {
					if (irList.get(i) != null && irList.get(i).getData() != null) {
						byte[] data = IrDnaSdkHelper.getIrCode(irList.get(i).getFreq(), irList.get(i).getData());
						String str = Util.bytesToHexString(data).toUpperCase();
						String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
						Log.e("wmy", "第"+i+ "条空调....###..解析出的红外数据..data = " + cmd);
						socket.sendMqttDataDelay(cmd);
						
					}
				}
				showAirState();
			}
		});
	}

	public void showMenu(View v) {
		LinearLayout linerLayout = new LinearLayout(RemoteActivity.this);
		final PopupWindow p = new PopupWindow(linerLayout, 600, 900);
		linerLayout.setOrientation(LinearLayout.VERTICAL);
		Button upLoad = new Button(RemoteActivity.this);
		upLoad.setText("上传此遥控器");
		Button deleteLocal = new Button(RemoteActivity.this);
		deleteLocal.setText("本地删除此遥控器");
		Button delServer = new Button(RemoteActivity.this);
		delServer.setText("服务端删除此遥控器");
		linerLayout.addView(upLoad);
		linerLayout.addView(deleteLocal);
		linerLayout.addView(delServer);
		p.setContentView(linerLayout);

		deleteLocal.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				p.dismiss();
				IRemoteManager manager = new RemoteManager();
				if (mRemote != null) {
					manager.deleteRemote(mRemote);
					Toast.makeText(RemoteActivity.this, "删除遥控器...",
							Toast.LENGTH_SHORT).show();
					IInfraredFetcher fetcher = new InfraredFetcher(
							RemoteActivity.this);
					fetcher.clearAirRemoteStatus(mRemote.getId());
					finish();
				}
			}
		});

		upLoad.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				p.dismiss();
				IRemoteClient client = new RemoteClient(RemoteActivity.this);
				client.uploadReomte(mRemote, new CallBackOnRemoteUploaded() {
					@Override
					public void onUploaded(int errcode, Remote newRemote) {
						if (errcode == CallBackOnRemoteUploaded.ERROR_CODE_NOT_LOGIN) {
							Toast.makeText(RemoteActivity.this, "未登录！",
									Toast.LENGTH_LONG).show();
						} else if (errcode == CallBackOnRemoteUploaded.ERROR_CODE_SUCCESS
								&& newRemote != null) {
							Toast.makeText(RemoteActivity.this, "上传成功！",
									Toast.LENGTH_LONG).show();
							mRemote = newRemote;
						} else {
							Toast.makeText(RemoteActivity.this, "上传失败！",
									Toast.LENGTH_LONG).show();
						}
					}
				});

			}
		});

		delServer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				p.dismiss();
				IRemoteClient remoteClient = new RemoteClient(
						RemoteActivity.this);
				// remoteClient.delete_remote(mRemote.getId(), new
				// CallBackOnRemoteDeleted() {
				// @Override
				// public void onDeleted(int errcode) {
				// if (errcode == CallBackOnRemoteDeleted.ERROR_CODE_NOT_LOGIN)
				// {
				// Toast.makeText(RemoteActivity.this, "未登录！",
				// Toast.LENGTH_LONG).show();
				// }
				// else if (errcode ==
				// CallBackOnRemoteDeleted.ERROR_CODE_SUCCESS)
				// {
				// Toast.makeText(RemoteActivity.this, "删除成功！",
				// Toast.LENGTH_LONG).show();
				// }
				// else
				// {
				// Toast.makeText(RemoteActivity.this, "删除失败！",
				// Toast.LENGTH_LONG).show();
				// }
				// }
				// });
			}
		});
		p.showAsDropDown(v);
	}

	/** 展示或刷新空调状态屏 ,这里只示范 模式，温度及风量的状态展示和刷新，其他状态类似 */
	void showAirState() {
		// 获取状态z
		// AirRemoteState state =
		// AirRemoteStateMananger.getInstance(getApplicationContext()).getAirRemoteState(mRemote.getId());
		IInfraredFetcher mFetcher = new InfraredFetcher(this);
		AirRemoteState state = mFetcher.getAirRemoteStatus(mRemote);

//		Log.i("wmy",
//				mRemote.getName() + " mState.getCaculate_number() = "
//						+ state.getCaculate_number()
//						+ " mState.getComfort() = " + state.getComfort()
//						+ " mState.getMode() = " + state.getMode()
//						+ " mState.getTemp() = " + state.getTemp().toString()
//						+ " mState.getTemp_display() = "
//						+ state.getTemp_display() + " mState.getWind_hoz() = "
//						+ state.getWind_hoz() + " mState.getWind_ver() = "
//						+ state.getWind_ver()
//						+ " mState.getWind_direction() = "
//						+ state.getWind_direction() + " mState.getSleep() = "
//						+ state.getSleep() + " mState.getFlash_air() = "
//						+ state.getFlash_air() + " mState.getHot() = "
//						+ state.getHot() + " mState.getPower_saving() = "
//						+ state.getPower_saving());

		if (state != null) {
			Log.i("wmy",
					"showAirState......##......state.power = "
							+ state.getPower() + " , state.mode = "
							+ state.getMode() + " , state.temp="
							+ state.getTemp() + " , state.wind_amount = "
							+ state.getWind_amount());
			initTemp = state.getTemp().value();
			switch (state.getPower()) {
			case POWER_ON:
				txtview_mode.setTextColor(Color.RED);
				txtview_temp.setTextColor(Color.BLUE);
				txtview_temp_symbol.setTextColor(Color.BLUE);
				txtview_wind_amout.setTextColor(Color.BLACK);

				break;

			default:
				txtview_mode.setTextColor(Color.GRAY);
				txtview_temp.setTextColor(Color.GRAY);
				txtview_temp_symbol.setTextColor(Color.GRAY);
				txtview_wind_amout.setTextColor(Color.GRAY);
				break;
			}

			switch (state.getMode()) {
			case WIND:
				txtview_mode.setText("送风");
				txtview_temp.setVisibility(View.GONE);
				txtview_temp_symbol.setVisibility(View.GONE);
				break;

			case COOL:
				txtview_mode.setText("制冷");
				txtview_temp.setVisibility(View.VISIBLE);
				txtview_temp_symbol.setVisibility(View.VISIBLE);
				txtview_temp.setText(String.valueOf(state.getTemp().value()));
				break;
			case HOT:
				txtview_mode.setText("取暖");
				txtview_temp.setVisibility(View.VISIBLE);
				txtview_temp_symbol.setVisibility(View.VISIBLE);
				txtview_temp.setText(String.valueOf(state.getTemp().value()));

				break;

			case DRY:
				txtview_mode.setText("抽湿");
				txtview_temp.setVisibility(View.GONE);
				txtview_temp_symbol.setVisibility(View.GONE);
				break;

			default:
				txtview_mode.setText("自动");
				txtview_temp.setVisibility(View.GONE);
				txtview_temp_symbol.setVisibility(View.GONE);
				break;
			}

			switch (state.getWind_amount()) {
			case LEVEL_1:
				txtview_wind_amout.setText("风量：一档");
				break;
			case LEVEL_2:
				txtview_wind_amout.setText("风量：二档");

				break;

			case LEVEL_3:
				txtview_wind_amout.setText("风量：三档");

				break;

			case LEVEL_4:
				txtview_wind_amout.setText("风量：四档");

				break;

			default:
				txtview_wind_amout.setText("风量：自动");

				break;
			}
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		DeviceManager.getInstance().setNeedToCheckTemp(true);
	}

	// 初始化按键
//	private void initKeys() {
////		Key key = null;
////		Key key1 = null;
////		for (int i = 0; i < mRemote.getKeys().size(); i++) {
////			if (mRemote.getKeys().get(i).getType() == 811) {
////				Log.i("wmy", "温度加");
////				key = mRemote.getKeys().get(i);
////			}
////			if (mRemote.getKeys().get(i).getType() == 812) {
////				key1 = mRemote.getKeys().get(i);
////			}
////		}
////		// 温度加
////		for (int i = initTemp; i < 30; i++) {
////			getKeyCode(mRemote, key, i);
////		}
////		for (int i = initTemp; i > 15; i--) {
////			getKeyCode(mRemote, key1, i);
////		}
//		InfraredFetcher mFetcher = new InfraredFetcher(this);
//		AirRemoteState state = mFetcher.getAirRemoteStatus(mRemote);
//		String t = state.getTemp().toString();
//		String mode = state.getMode().toString();
//		for (int n = 16; n < 33; n++) {
////			mFetcher.f
//			AirRemoteState mState = new AirRemoteState(mRemote.getId());
////			List<Infrared> irList = mFetcher.f
//			List<Infrared> irList = mFetcher.fetchAirInfrareds(mRemote, mState, mState.getPower(), mState.getMode(),
//					mState.getWind_amount(), AirTemp.getAirTemp(n));
//			for (int i = 0; i < irList.size(); i++) {
//				if (irList.get(i) != null && irList.get(i).getData() != null) {
//					byte[] data = IrDnaSdkHelper.getIrCode(irList.get(i).getFreq(), irList.get(i).getData());
//					String str = Util.bytesToHexString(data).toUpperCase();
//					String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
//					cmdMap.put(n, cmd);
//					showAirState1();
//					Log.e("wmy", "空调....###..解析出的红外数据..data = " + cmd);
//				}
//			}
//			// Log.i("wmy", "irList = " + irList.size());
//		}
//	}
	
	private void showAirState1(){
		IInfraredFetcher mFetcher = new InfraredFetcher(this);
		AirRemoteState state = mFetcher.getAirRemoteStatus(mRemote);
	}

	private void getKeyCode(Remote remote, Key key, int num) {
		if (remote == null || remote.getId() == null || key == null) {
			return;
		}

		List<Infrared> infrareds = null;

		// infrareds = mFetcher.fetchAirInfrareds(remote, key,
		// mFetcher.getAirRemoteStatus(remote));
		// AirRemoteState state = mFetcher.getAirRemoteStatus(remote);
		// byte[] pack = PackAirUtils.packAirState(state);

		// infrareds = mFetcher.fetchInfrareds(remote, key);
		infrareds = new InfraredFetcher(getApplicationContext())
				.fetchInfrareds(remote, key);
		if (infrareds != null) {
			for (Infrared ir : infrareds) {
				if (ir != null && ir.getData() != null) {
					int freq = ir.getFreq();
					// Required ！ 必须调用，此接口将对信号格式进行验证，返回明码信号数据
					byte[] data = IrDnaSdkHelper.getIrCode(ir.getFreq(),
							ir.getData());
					byte[] airData = IrDnaSdkHelper.getAirVMCode(key
							.getProtocol());
					String str = Util.bytesToHexString(data).toUpperCase();
					String cmd = ConvertUtil.getInstance().convertInfraredCmd(
							str);
					// String cmd = getInfraRedCmd(data);
					// data格式详见《信号数据格式说明》文档，不同的芯片需要转换成对应的芯片目标码
					Log.e("wmy", "获取 " + num + "的红外信号 = " + cmd);
					cmdMap.put(num, cmd);
					// SocketManager.getInstance().getSocket()
					// .sendMqttDataDelay(cmd);
					if (data != null) {
						// 测试
						// Toast.makeText(ct, "发送信号数据长度为："+data.length,
						// Toast.LENGTH_LONG).show();
						mDevice.sendIr(freq, data);

						// 多组信号发送时暂停一点时间，以避免信号连续发送而电器识别错误
						try {
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	/** ListView按键 */
	static class KeyAdapter extends BaseAdapter {
		Context mContext;
		LayoutInflater mInflater;
		Remote mRemote;
		IInfraredSeneder mSeneder;
		CallbackOnInfraredSended mCallbackOnInfraredSended;

		public KeyAdapter(Context context, Remote remote,
				CallbackOnInfraredSended callback) {
			mContext = context;
			mInflater = LayoutInflater.from(mContext);
			mSeneder = new InfraredSeneder(mContext);
			mRemote = remote;
			mCallbackOnInfraredSended = callback;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (mRemote != null && mRemote.getKeys() != null) {
				return mRemote.getKeys().size();
			}
			return 0;
		}

		@Override
		public Key getItem(int position) {
			// TODO Auto-generated method stub
			if (mRemote != null && mRemote.getKeys() != null) {
				return mRemote.getKeys().get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null)// 初始化一条item
			{
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_item_key, parent,
						false);
				holder.txt_key_name = (TextView) convertView
						.findViewById(R.id.txt_key_name);
				holder.txt_infrared_count = (TextView) convertView
						.findViewById(R.id.txt_infrared_count);
				holder.btn_send = (Button) convertView
						.findViewById(R.id.btn_send);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// 获取单个按键
			// mRemote.getKeys() 通过遥控器的实例拿到里面的按键
			final Key key = mRemote.getKeys().get(position);

			if (key != null) {
				holder.txt_key_name.setText(RemoteUtils.getKeyName(key
						.getType()));
				holder.txt_infrared_count
						.setText(String.valueOf(key.getInfrareds() == null ? 0
								: key.getInfrareds().size()) + " 个信号");
			} else {
				holder.txt_key_name.setText("未知按键");
			}

			holder.btn_send.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.i("wmy",
							"点击了 = " + key.getType() + " " + key.getLocalName());
					 mSeneder.send(mRemote, key);
//					if (key.getType() == 811) {
//						SocketManager.getInstance().getSocket()
//								.sendMqttData(cmdMap.get(initTemp + 1));
//					} else if (key.getType() == 812) {
//						SocketManager.getInstance().getSocket()
//								.sendMqttData(cmdMap.get(initTemp - 1));
//					} else {
//						mSeneder.send(mRemote, key);
//					}

					// 调用发送接口
					mCallbackOnInfraredSended.onInfrardSended();
				}
			});
			return convertView;
		}

		public final class ViewHolder {
			public TextView txt_key_name;
			public TextView txt_infrared_count;
			public Button btn_send;
		}

	}

	@Override
	public void onInfrardSended() {
		// TODO Auto-generated method stub
		// 如果是空调遥控器，则刷新状态屏
		if (mRemote != null
				&& mRemote.getType() == ApplianceType.AIR_CONDITIONER) {
			showAirState();
		}

	}

}
